package mysql

import (
	"crypto/md5"
	"encoding/hex"

	"douyin/models"

	"gorm.io/gorm"
)

const secret = "hello my friend"

// CheckUserExist 检查指定用户名的用户是否存在
func CheckUserExist(username string) (err error) {
	//sqlStr := `select count(user_id) from user where username = ?`
	//var count int64
	//if err := db.Get(&count, sqlStr, username); err != nil {
	//	return err
	//}
	var count int64
	tx := db.Debug().Model(&models.User{}).Where("username=?", username).Count(&count)
	if tx.Error != nil {
		return tx.Error
	}
	if count > 0 {
		return ErrorUserExist
	}
	return
}

// InsertUser 向数据库中插入一条新的用户记录
func InsertUser(user *models.User) (err error) {
	// 对密码进行加密
	user.Password = encryptPassword(user.Password)
	// 执行SQL语句入库
	//sqlStr := `insert into user(user_id, username, password) values(?,?,?)`
	//if _, err = db.Exec(sqlStr, user.Id, user.Name, user.Password); err != nil {
	//	return err
	//}
	//Omit:除了选择的字段都创建
	//Seclect:只创建选择的字段
	tx := db.Debug().Model(&models.User{}).Select("Id", "Name", "NickName", "Password").Create(user)
	if tx.Error != nil {
		return tx.Error
	}
	return
}

// Login 用户登录
func Login(user *models.User) (err error) {
	oldPassword := user.Password // 用户登录的密码
	//sqlStr := `select user_id, username, password from user where username=?` //通过用户名查找用户
	//err = db.Get(user, sqlStr, user.Name)                                     //从数据库中查出来的user覆盖了原来的user
	//if err == sql.ErrNoRows {
	//	return ErrorUserNotExist
	//}
	//if err != nil { // 查询数据库失败
	//	return err
	//}
	tx := db.Debug().Model(&models.User{}).Where("username = ?", user.Name).First(user)
	if tx.Error == gorm.ErrRecordNotFound {
		return ErrorUserNotExist
	}
	if tx.Error != nil {
		return tx.Error
	}
	// 判断密码是否正确
	passwordFromRequest := encryptPassword(oldPassword)
	if passwordFromRequest != user.Password {
		return ErrorInvalidPassword
	}
	return
}

// GetUserInfoByUserId 通过id查询用户信息
func GetUserInfoByUserId(userId, otherId int64) (user models.User, err error) {
	tx := db.Debug().Model(&models.User{}).Where("user_id = ?", otherId).Find(&user)
	if user.Id == 0 { //查不到对方
		err = ErrorQueryZeroRecord
		return
	}
	if tx.Error != nil {
		err = ErrorQueryFailed
		return
	}
	//查询用户与自己的关系
	follow := WhetherFollow(userId, otherId) //自己id,对方id
	user.IsFollow = follow
	return
}

// encryptPassword 密码加密
func encryptPassword(oPassword string) string {
	hash := md5.New()
	hash.Write([]byte(secret))
	return hex.EncodeToString(hash.Sum([]byte(oPassword)))
}
